package main

import (
	"fmt"
	"github.com/wendy512/go-iecp5/asdu"
	"github.com/wendy512/iec104/app"
	"github.com/wendy512/iec104/client"
	"time"
)

const (
	commonAddr = 1
)

type Client_My struct {
	c *client.Client
}

func NewClient_My(c *client.Client) *Client_My {
	return &Client_My{c: c}
}

func Client_init() *Client_My {
	settings := client.NewSettings()
	settings.LogCfg = &client.LogCfg{Enable: true}
	myclient := app.NewIecMyclient()
	c := client.New(settings, myclient)
	c.SetOnConnectHandler(func(c *client.Client) {
		// 连接成功以后做的操作
		fmt.Printf("connected %s iec104 server\n", settings.Host)
	})
	my := NewClient_My(c)
	// server active确认后回调
	c.SetServerActiveHandler(func(c *client.Client) {
		//// 发送总召唤
		if err := c.SendInterrogationCmd(commonAddr); err != nil {
			fmt.Errorf("send interrogation cmd error %v\n", err)

		}

		// 累积量召唤
		if err := c.SendCounterInterrogationCmd(commonAddr); err != nil {
			fmt.Errorf("send counter interrogation cmd error %v\n", err)
		}

		// read cmd
		if err := c.SendReadCmd(commonAddr, 100); err != nil {
			fmt.Errorf("send counter interrogation cmd error %v\n", err)
		}

		// 时钟同步
		if err := c.SendClockSynchronizationCmd(commonAddr, time.Now()); err != nil {
			fmt.Errorf("send clock sync cmd error %v\n", err)
		}

		// test cmd
		if err := c.SendTestCmd(commonAddr); err != nil {
			fmt.Errorf("send test cmd error %v\n", err)
		}

		// 单点控制
		if err := c.SendCmd(commonAddr, asdu.C_SC_NA_1, asdu.InfoObjAddr(1000), false); err != nil {
			fmt.Errorf("send single cmd error %v\n", err)
		}
	})
	return my
}

func main() {
	init := Client_init()

	if err := init.c.Connect(); err != nil {
		fmt.Errorf("client connect error %v\n", err)
	}
	for {
		time.Sleep(time.Second)
	}
}
